<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import LuckyExcel from 'luckyexcel'
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {getUserInfo} from "@/utils/auth.ts";
// import CapacityBDetail from "@/components/analysisSheetComponents/waterCapacity/capacity/capacityBDetail.vue";
import CapacityBDetail from "@/components/analysisSheetComponents/waterCapacity/tmpl52/index.vue"

const waterForm = ref({
  sampling_time: "", // 采样日期
  b_rypz: {},
  b_bdgc: {},
  b_kbjc: {},
  b_pxycd: {},
  b_bzycd: {},
  b_jbhsy: {},
  b_notes: '',
  b_bdrq: ''
})
const checkForm = ref({
  result: "",
  review_content: "",
})
const reviewForm = ref({
  result: "",
  review_content: "",
})
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const checkDialogVisible = ref(false)
const reviewDialogVisible = ref(false)
const checkTime = ref('')
const userInfo = JSON.parse(getUserInfo())

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "row": 9,
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // B1
        {"r": 0, "c": 2, "v": "取样体积V(mL)",}, // B1
        {"r": 0, "c": 3, "v": "稀释倍数f",}, // B1
        {"r": 0, "c": 4, "v": "标准溶液消耗体积(mL)",}, // B1
        {"r": 0, "c": 8, "v": "样品浓度C(mg/L)",}, // B1
        {"r": 0, "c": 9, "v": "备注",}, // B1
        {"r": 1, "c": 4, "v": "始读数",}, // B1
        {"r": 1, "c": 5, "v": "终读数",}, // B1
        {"r": 1, "c": 6, "v": "V1",}, // B1
        {"r": 1, "c": 7, "v": "净含量",}, // B1
      ], // 初始化数据
      "config": {
        "merge": {
          "0_0": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_1": {
            "r": 0, // 起始行
            "c": 1, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_2": {
            "r": 0, // 起始行
            "c": 2, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_3": {
            "r": 0, // 起始行
            "c": 3, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_4": {
            "r": 0,  // 起始行
            "c": 4,  // 起始列
            "rs": 1, // 跨越的行数
            "cs": 4  // 跨越的列数
          }
        }, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 100, // 第五列宽度 200px
          "5": 100,  // 第六列宽度 150px
          "6": 100,  // 第六列宽度 150px
          "7": 100,  // 第六列宽度 150px
          "8": 100,  // 第六列宽度 150px
          "9": 100,  // 第六列宽度 150px
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: false, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 调用 Luckysheet 内建方法添加行
  luckysheet.insertRow();  // 默认在表格最后添加一行
  // 获取初始数据并保存在响应式变量中
//   获取表单信息
  getWaterCapacity()
});

const loadDataFromLocal = () => {
  checkDialogVisible.value = true
};

const loadDataFromLocalReview = () => {
  reviewDialogVisible.value = true
}

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  AnalyesAPI.getAnalyseACapacity({id: analyseStatusPage.waterForm.id, record_sn: record_sn.value}).then(data => {
    console.log('获取水质容量 A单', data)
  })
}

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }
  // 提取表头字段
  const headers = [];
  for (let i = 0; i < data[0].length; i++) {
    const field1 = data[0][i]?.field || ""; // 第一行的字段
    const field2 = data[1][i]?.field || ""; // 第二行的字段

    // 优先使用第二行字段，如果为空则使用第一行字段
    const header = (field1 === "默认字段" || field1 === "") ? field2 : field1;

    // 跳过无效字段
    if (header !== "默认字段" && header.trim() !== "") {
      headers.push(header);
    }
  }

  console.log(headers)
  // 处理数据部分
  const result = data.slice(2).map(row => {
    const rowObject = {};
    headers.forEach((header, index) => {
      const cell = row[index];
      rowObject[header] = cell?.value ?? null; // 如果没有值，则默认 null
    });
    return rowObject;
  });

  // 过滤掉空行（所有字段均为 null 的行）
  return result.filter(row =>
      Object.values(row).some(value => value !== null)
  );
};

function formatLuckysheetData(sheetData) {
  const formattedData = [];
  // 假设第一行为标题行
  const headers = sheetData[0].cells.map(cell => cell.v);
  // 遍历每一行数据（从第二行开始）
  for (let i = 1; i < sheetData.length; i++) {
    const row = sheetData[i];
    const rowData = {};
    // 将每行的数据映射到对象属性
    row.cells.forEach((cell, index) => {
      rowData[headers[index]] = cell.v;
    });
    formattedData.push(rowData);
  }
  return formattedData;
}

// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true
};
const handleCheckClose = () => {
  checkDialogVisible.value = false
}

// 取消审核
const handleReviewClose = () => {
  reviewDialogVisible.value = false
}

// 确认提交
const handleSubmit = () => {
  let json = {
    ...checkForm.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id
  }
  AnalyesAPI.handleCheckList(json).then(data => {
    console.log('提交校核', data)
    checkDialogVisible.value = false
  })
}

// 确认提交审核
const handleReviewSubmit = () => {
  let json = {
    ...reviewForm.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id
  }
  AnalyesAPI.handleReviewList(json).then(data => {
    console.log('提交审核', data)
    reviewDialogVisible.value = false
  })
}

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files
  console.log(files)
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }
  let name = files[0].name
  let suffixArr = name.split('.'),
      suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson.sheets)
    jsonData.value = exportJson

    luckysheet.destroy()
    luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}

const handleSwitch = () => {
  switchAB.value = !switchAB.value
}
</script>

<template>
  <div class="card">
    <div v-show="switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">水质 容量法分析原始记录(A面)</h1>
        <table class="table">
          <tr style="background-color: #f2f2f2">
            <td>任务编号</td>
            <td>
              {{ waterForm.task_name }}
            </td>
            <td>采样日期</td>
            <td>
              {{ waterForm.sampling_time }}
            </td>
            <td>分析日期</td>
            <td>
              {{ waterForm.anal_time }}
            </td>
          </tr>
          <tr>
            <td>监测指标</td>
            <td colspan="3">
              {{ waterForm.jc_index }}
            </td>
            <td>检出限</td>
            <td>
              {{ waterForm.limit_val }}
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>分析方法</td>
            <td colspan="5">{{ waterForm.method }}
            </td>
          </tr>
          <tr>
            <td>分析仪器</td>
            <td>
              <!--              <el-select-->
              <!--                  multiple-->
              <!--                  filterable-->
              <!--                  remote-->
              <!--                  reserve-keyword-->
              <!--                  placeholder="请选择内容"-->
              <!--                  style="width: 100%"-->
              <!--              >-->
              <!--                <el-option-->
              <!--                    v-for="item in tableOption"-->
              <!--                    :key="item.id"-->
              <!--                    :label="item.label"-->
              <!--                    :value="item.id"-->
              <!--                />-->
              <!--              </el-select>-->
              {{ waterForm.device_name }}
            </td>
            <td>仪器型号</td>
            <td>
              {{ waterForm.device_model }}
            </td>
            <td>仪器编号</td>
            <td>
              {{ waterForm.device_number }}
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>环境温度</td>
            <td>
              {{ waterForm.temperature }}℃
            </td>
            <td>环境湿度</td>
            <td>
              {{ waterForm.humidity }}%RH
            </td>
            <td>样品类别</td>
            <td>
              {{ waterForm.category_id }}
            </td>
          </tr>
          <tr>
            <td>标准溶液名称</td>
            <td colspan="2">
              {{ waterForm.bz_ryname }}
            </td>
            <td>基准溶液名称</td>
            <td colspan="2">
              {{ waterForm.jz_ryname }}
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>标准溶液浓度C0(mol/L)</td>
            <td colspan="2">
              {{ waterForm.bz_rynd }}
            </td>
            <td>基准溶液浓度C1(mol/L)</td>
            <td colspan="2">

              {{ waterForm.jz_rynd }}
            </td>
          </tr>
          <tr>
            <td>计算公式</td>
            <td colspan="5">

              {{ waterForm.js_formula }}
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>前处理过程</td>
            <td colspan="5">

              {{ waterForm.process }}
            </td>
          </tr>
          <tr>
            <td colspan="6">
              <div class="table-td" style="display: flex;align-items: center">
                <div>项目详情</div>
                <div>
                  <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                  />
                </div>
              </div>
            </td>
          </tr>
        </table>
        <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
        <div id="luckysheet" style="width:100%;height:500px;"></div>
      </el-card>
    </div>
    <div v-show="!switchAB">
      <capacity-b-detail :waterForm="waterForm"></capacity-b-detail>
    </div>

    <el-card class="box-card" style="margin-top: 30px">
      <div style="display: flex;justify-content: space-between;">
        <el-button @click="handleSwitch">
          {{ switchAB ? 'B面' : 'A面' }}
        </el-button>
        <div>
          <el-button>取消</el-button>
          <!--          <el-button>新增</el-button>-->
          <!--          <el-button>复制并新增</el-button>-->
          <el-button @click="loadDataFromLocal" v-if="userInfo.id === analyseStatusPage.waterForm.tableItem.check_uid">
            校核
          </el-button>
          <el-button @click="loadDataFromLocalReview"
                     v-if="userInfo.id === analyseStatusPage.waterForm.tableItem.check_uid">
            审核
          </el-button>
        </div>
      </div>
    </el-card>

    <!--    提交校核-->
    <el-dialog title="提交校核" v-model="checkDialogVisible" width="30%" center
               :before-close="handleCheckClose">
      <div class="check">
        <div style="display: flex;align-items: center;margin-bottom: 20px">
          校核结果：
          <el-radio-group v-model="checkForm.result">
            <el-radio value="1" size="large">同意</el-radio>
            <el-radio value="0" size="large">拒绝</el-radio>
          </el-radio-group>
        </div>
        <div style="display: flex;align-items: center;margin-bottom: 20px">
          <span style="width: 120px;">驳回原因：</span>
          <el-input style="border: 1px solid #ccc;border-radius: 6px" v-model="checkForm.review_content"
                    placeholder="请输入驳回原因"></el-input>
        </div>
        <div class="check-footer">
          <el-button style="width: 48%;" @click="handleCheckClose">取消</el-button>
          <el-button type="primary" style="width: 48%;" @click="handleSubmit">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <!--    提交审核-->
    <el-dialog title="提交审核" v-model="reviewDialogVisible" width="30%" center
               :before-close="handleReviewClose">
      <div class="check">
        <div style="display: flex;align-items: center;margin-bottom: 20px">
          审核结果：
          <el-radio-group v-model="reviewForm.result">
            <el-radio value="1" size="large">同意</el-radio>
            <el-radio value="0" size="large">拒绝</el-radio>
          </el-radio-group>
        </div>
        <div style="display: flex;align-items: center;margin-bottom: 20px">
          <span style="width: 120px;">驳回原因：</span>
          <el-input style="border: 1px solid #ccc;border-radius: 6px" v-model="reviewForm.review_content"
                    placeholder="请输入驳回原因"></el-input>
        </div>
        <div class="check-footer">
          <el-button style="width: 48%;" @click="handleReviewClose">取消</el-button>
          <el-button type="primary" style="width: 48%;" @click="handleReviewSubmit">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
